<template>
  <!-- 购物车页面 -->
  <div class="carts">
    <!-- 标题 -->
    <div class="title">{{ $t("cart.title") }}</div>
    <!-- 购物车 -->
    <div class="cart" v-show="cartList.length !== 0">
      <van-swipe-cell v-for="(product, index) in cartList" :key="product.cartId">
        <div class="flex-container">
          <van-checkbox v-model="selectedProducts[index]" class="checkbox" />
          <div class="card-container">
            <van-card :price="product.commodityPrice.toFixed(2)"
              :desc="formatSpecification(product.commoditySpecstring)" :title="product.commodityName" class="goods-card"
              :thumb="product.commodityImg">
              <template #tags>
                <div>库存：{{ product.inventory }}</div>
              </template>

              <template #bottom>
                <van-tag plain @click="goDetail(product.commodityId)" type="primary">详情</van-tag>
              </template>
              <template #footer>
                <van-stepper v-model="product.commodityCount" integer min="1" max="99" />
              </template>
            </van-card>
          </div>
        </div>
        <template #right>
          <van-button square text="删除" type="danger" style="height: 100%" class="delete-button"
            @click="removeProduct(index)" />
        </template>
      </van-swipe-cell>
    </div>
    <view v-show="cartList.length === 0">
      <van-empty description="暂时没有商品" />
    </view>
    <van-submit-bar class="submit-bar" :price="totalPrice" button-text="提交订单" button-color="#6a0dad" @submit="onSubmit">
      <van-checkbox v-model="checked" @change="toggleAll" /> 全选
      <van-button text="删除" size="small" round type="danger" style="margin-left: 10rem" @click="removeSelected" />
    </van-submit-bar>
    <div v-show="showPopups" class="box300">Please select product</div>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import { ref, watch, computed, onActivated, nextTick, onMounted } from "vue";


import { deleteAPI } from "@/server/api/cartView";
import { formatSpecification } from "@/utils/formatSpecFun"
import { useUseStore } from "@/stores/user";
import { orderStatus } from "@/stores/payStore";
import { useCartPage } from "@/stores/cartStorePage";
import { useIndexStore } from "@/stores/indexStore";

import { ToastFun } from "@/hook/toast";
import { cartListAPI } from "@/server/api/cartView";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const router = useRouter();

let useCart = useCartPage();
let useStore = useUseStore();
const selectedProducts = ref([]); // 用于控制选择框的状态
const checked = ref(false); // 全选状态

const cartList = ref([])
//总价
const totalPrice = computed(() => {
  const products = cartList.value.filter(
    (_, index) => selectedProducts.value[index]
  );
  const totalPrice = products.reduce((accumulator, product) => {
    if (
      typeof product.commodityPrice !== "number" ||
      typeof product.commodityCount !== "number"
    ) {
      return accumulator;
    }
    return (
      accumulator +
      parseFloat(product.commodityPrice).toFixed(2) * product.commodityCount
    );
  }, 0);
  return totalPrice * 100;
});



//全选状态
const toggleAll = (e) => {
  checked.value = e;
  selectedProducts.value = cartList.value.map(() => e);
};

//单删除
const removeProduct = async (index) => {
  try {
    ToastFun("Loading", { duration: 0 });
    let cartIds = [];
    let cartId = cartList.value[index].cartId;
    cartIds.push(cartId);
    const res = await deleteAPI(useStore.userId, cartIds);
    if (res.data.code === 200) {
      ToastFun("show", { msg: res.data.data });
      cartList.value.splice(indexs, 1);
      getCartListFun(useStore.userId);
      checkboxStatu();
    } else {
      ToastFun("show", { msg: res.data.data });
    }
  } catch (error) {
    ToastFun("fail", { msg: t("item.details.NetworkError") });
  }
};

//全选删除
const removeSelected = async () => {
  try {
    const products = cartList.value.filter(
      (_, index) => selectedProducts.value[index]
    );
    if (products.length !== 0) {
      ToastFun("Loading", { duration: 0 });
      const cartIds = products.map((product) => product.cartId);
      const res = await deleteAPI(useStore.userId, cartIds);
      if (res.data.code === 200) {
        ToastFun("show", { msg: res.data.data });
        cartList.value.filter((_, index) => !selectedProducts.value[index]);
        getCartListFun(useStore.userId);
        checkboxStatu(); // 更新选择状态
      } else {
        ToastFun("show", { msg: res.data.data });
      }
    } else {
      showPopups.value = true;
      setTimeout(() => {
        showPopups.value = false;
      }, 1500);
    }
  } catch (error) {
    ToastFun("fail", { msg: t("item.details.NetworkError") });
  }
};

// 监视，
watch(
  () => selectedProducts.value,
  (newValue) => {
    const allTrue = Object.values(newValue).every((value) => value === true);
    checked.value = allTrue;
  },
  { deep: true }
);

let timer = ref(null);
let indexs = ref(null);
const showPopup = ref(false);
const showPopups = ref(false);

// 点击跳转Order页面
const onSubmit = () => {
  const selectedItems = cartList.value.filter(
    (_, index) => selectedProducts.value[index]
  );
  console.log(selectedItems, "shuju ");
  if (selectedItems.length !== 0) {
    // 格式化选中的商品数据
    const orderItems = selectedItems.map((item) => ({
      shopId: item.shopId,
      avatarImag: item.commodityImg,
      number: Number(item.commodityCount),
      price: item.commodityPrice,
      commodityId: item.commodityId,
      discount: item.commodityPrice, // 这里假设原价和折扣价一致
      commoditySpecification: item.commoditySpecstring,
      itemCommodityName: item.commodityName,
      skuId: item.skuId
    }));
    console.log(orderItems, "订单数据");

    // # 生成网店商品未支付订单的请求体，并且存入状态管理库
    orderStatus().itmeOrderReq = {
      uid: useStore.userId,
      buyerDataId: null,
      itemOrderDetailDTOList: orderItems,
    };

    // # 将状态管理库的订单类型修改为网店类型，使得页面调用对应的接口
    orderStatus().orderType = "item";
    console.log(orderStatus().itmeOrderReq, "传的数")
    router.push({ name: "ConfirmOrder" });
  } else {
    showPopups.value = true;
    setTimeout(() => {
      showPopups.value = false;
    }, 1500);
  }
};

// 跳转商品详情
const goDetail = (id) => {
  router.push({
    path: "/details",
    query: {
      id,
    },
  });
};

//获取购物车数据
const getCartListFun = async (userId) => {
  try {
    const res = await cartListAPI(userId);
    if (res.data.code === 200) {
      cartList.value = res.data.data;
      selectedProducts.value = cartList.value.map(() => false); // 初始化为未选中
      console.log("购物车数据", cartList.value);
    }
  } catch (error) {
    ToastFun("show", { msg: t("item.details.NetworkAnomaly") });
  }
}

onMounted(() => {
  getCartListFun(useStore.userId);
});

//组件激活
onActivated(() => {
  getCartListFun(useStore.userId);
});



nextTick(() => { });

</script>

<style lang="scss" scoped>
.carts {
  overflow: hidden;

  .title {
    position: fixed;
    z-index: 9;
    display: flex;
    align-items: center;
    font-size: 20rem;
    height: 80rem;
    width: 100%;
    padding: 0 16rem;
    background-color: #fff;
  }

  .cart {
    position: fixed;
    top: 0;
    bottom: 0;
    overflow-y: auto;
    width: 390rem;
    padding-bottom: 150rem;
    background-color: rgba(245, 245, 245, 1);
    padding-top: 100rem;

    .item {
      width: 390rem;
      height: 142rem;
      background-color: #fff;
      display: flex;
      position: relative;

      img {
        width: 102rem;
        height: 118rem;
        border-radius: 12rem;
        margin: 12rem 16rem;
      }

      .right {
        padding: 12rem 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .trade {
          width: 210rem;
          font-size: 14rem;
          font-weight: 550;
          color: rgba(51, 51, 51, 1);
          height: 20rem;
          overflow: hidden;
          -webkit-line-clamp: 1;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          text-align: left;
        }

        .goodsStyle {
          font-size: 14rem;
          font-weight: 400;
          line-height: 20rem;
          color: rgba(153, 153, 153, 1);
        }

        .price {
          margin-left: 70rem;
          margin-top: 12rem;
          font-size: 14rem;
          font-weight: 550;
          color: rgba(51, 51, 51, 1);

          span {
            font-size: 16rem;
            font-weight: 550;
            color: rgba(100, 46, 142, 1);
            margin-left: 5rem;
          }
        }
      }

      .checkBox {
        position: absolute;
        top: 14rem;
        right: 16rem;
      }

      .sub_plus {
        display: flex;

        position: absolute;
        bottom: 16rem;
        right: 16rem;

        &.is_rtl {
          left: 16rem;
          right: unset;
        }

        div {
          width: 20rem;
          height: 22rem;
          background: rgba(255, 255, 255, 1);
          line-height: 22rem;
          text-align: center;
          font-size: 18rem;
          border: 1rem solid rgba(229, 229, 229, 1);
        }

        .sub {
          border-radius: 4rem 0 0 4rem;
        }

        .count {
          font-size: 14rem;
        }

        .plus {
          border-radius: 0 4rem 4rem 0;
        }
      }
    }
  }

  .popup {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.5);
    border: 1rem solid #ccc;
    display: flex;
    width: 100%;
    height: 100%;
    justify-content: center;
    align-items: center;
    z-index: 9;

    .Delete {
      background-color: #fff;
      font-size: 16rem;
      border: none;
      border-radius: 99rem;
      padding: 13rem 48rem;
    }
  }

  .box300 {
    background-color: rgba(0, 0, 0, 0.7);
    font-size: 16rem;
    border: none;
    border-radius: 99rem;
    padding: 13rem 48rem;
    z-index: 9;
    position: fixed;
    bottom: 150rem;
    left: 60rem;
    color: #fff;
  }

  // 所有的checkbox
  input[type="checkbox"] {
    width: 20rem;
    height: 20rem;
    background-color: #fff;
    appearance: none;
    border: 1rem solid #c9c9c9;
    border-radius: 50%;
    outline: none;
  }

  // 选中状态
  input[type="checkbox"]:checked {
    background-color: rgba(100, 46, 142, 1);
  }

  .checkOut {
    width: 100%;
    height: 78rem;
    background-color: #fff;
    position: fixed;
    bottom: 50rem;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .deleteSelect {
      border-radius: 20rem;
      background: rgb(241, 34, 34);
      color: rgba(255, 255, 255, 1);
      line-height: 16rem;
      font-size: 14rem;
      margin-left: 16rem;
      padding: 5rem 10rem;
    }

    .CheckAll {
      display: flex;
      height: 23rem;
      font-size: 15rem;
      font-weight: 400;
      line-height: 26rem;
      margin-left: 16rem;
      color: rgba(153, 153, 153, 1);

      input {
        margin: 0 5rem;
      }
    }

    .total {
      margin-left: 18rem;
      font-size: 16rem;
      color: rgba(51, 51, 51, 1);

      span {
        font-size: 16rem;
        font-weight: 600;
      }
    }

    .btn {
      border-radius: 27rem;
      background: rgba(100, 46, 142, 1);
      color: rgba(255, 255, 255, 1);
      line-height: 36rem;
      font-size: 14rem;
      right: 12rem;
      padding: 5rem 30rem;
    }
  }
}

.flex-container {
  padding-left: 10rem;
  display: flex;
  align-items: center;
  /* 垂直居中对齐 */
  background-color: white;
}

.checkbox {
  margin-right: 10px;
  /* 调整选择框和卡片之间的间距 */
  flex: 0 0 auto;
  /* 选择框不伸缩 */
}

.card-container {
  flex: 1;
  /* 商品卡片占据剩余空间 */
}

.goods-card {
  background-color: white;
  /* 设置背景颜色为白色 */
}

.submit-bar {

  width: 100%;
  height: 80rem;
  position: fixed;
  bottom: 60rem;

}

/* 修改按钮的颜色 */
.submit-bar .van-button--danger {
  background-color: #8a2be2;
  /* 紫色背景 */
  border-color: #8a2be2;
  /* 边框颜色匹配 */
}

/* 全选文字颜色 */
.submit-bar .van-checkbox {
  color: #fff;
  /* 白色文字 */
}

/* 提示信息的文字和链接样式 */
.submit-bar .link {
  color: #ffccff;
  /* 浅紫色链接 */
  cursor: pointer;
  /* 鼠标变成手型 */
  text-decoration: underline;
  /* 添加下划线 */
}

/* 删除按钮的额外样式 */
.delete-button {
  margin-left: 10px;
  /* 调整间距 */
  color: #fff;
  /* 白色字体 */
}
</style>